package com.inspinia.upms.server.controller;

import com.inspinia.auth.rpc.api.AuthService;
import com.inspinia.base.cache.RedisUtil;
import com.inspinia.base.common.model.AjaxResult;
import com.inspinia.base.common.model.BaseConstants;
import com.inspinia.base.common.model.Status;
import com.inspinia.base.common.model.UserCacheKeys;
import com.inspinia.base.pagination.Pager;
import com.inspinia.base.util.CollectionUtil;
import com.inspinia.base.util.JsonUtils;
import com.inspinia.base.util.StringUtils;
import com.inspinia.config.common.config.SystemConfig;
import com.inspinia.message.common.model.NoticeLinkType;
import com.inspinia.message.rpc.api.NoticeService;
import com.inspinia.upms.common.model.app.App;
import com.inspinia.upms.common.model.app.AppVo;
import com.inspinia.upms.common.model.resource.UpmsResource;
import com.inspinia.upms.common.model.user.UpmsUser;
import com.inspinia.upms.rpc.api.ApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.beans.PropertyEditorSupport;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 获取资源
 * @author Administrator
 */
@Controller
@Api(value = "/ManageController", tags = "系统首页资源菜单管理")
@RequestMapping(value = "upms/manage/")
public class ManageController {

    @Resource
    AuthService authService;

    @Resource
    ApplicationService applicationService;

    @Resource
    NoticeService noticeService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Status.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                Status status = Status.valueOf(Integer.valueOf(text));
                setValue(status);
            }
        });
    }
    /**
     * 获取用户权限
     * @return
     */
    @ResponseBody
    @GetMapping(value = "getMenus")
    @ApiOperation(value = "获取权限菜单", notes = "获取权限菜单", httpMethod = "GET", response = AjaxResult.class)
    public AjaxResult getMenus() {
        UpmsUser principal = authService.getUserByPrincipal(SecurityUtils.getSubject().getPrincipals());
        if (null != principal) {
            String key = UserCacheKeys.getUserMenuKey(principal.getUserId());
            String val = RedisUtil.get(key);
            List<UpmsResource> resources = null;
            if (StringUtils.isEmpty(val)) {
                resources = authService.findResourcesByUser(principal.getUserId());
                if (CollectionUtil.isNotEmpty(resources)){
                    noticeService.push(1L,NoticeLinkType.noticeCount,null,"新的消息通知");
                    //只要对应系统的资源
                    App appByName = applicationService.findAppByName(SystemConfig.systemIndexTitleName);
                    resources = resources.stream().filter(r -> Objects.nonNull(r.getAppId()) && r.getAppId() == appByName.getId()).collect(Collectors.toList());
                    RedisUtil.setObj(key,resources,BaseConstants.REDIS_KEY_EXPIRE_30_M);
                }
                return new AjaxResult(resources) ;
            }else {
                resources = JsonUtils.fromJsonList(val, UpmsResource.class);
            }
            return new AjaxResult(true,resources);
        }
        return null;
    }

    /**
     * 获取某个系统的权限菜单
     * @return
     */
    @ResponseBody
    @GetMapping(value = "getMenusByAppName")
    public AjaxResult getMenusByAppName(String appName) {
        UpmsUser principal = authService.getUserByPrincipal(SecurityUtils.getSubject().getPrincipals());
        if (null != principal) {
            //用户拥有的资源
            List<UpmsResource> resourcesByUser = authService.findResourcesByUser(principal.getUserId());
            //只要对应系统的资源
            App appByName = applicationService.findAppByName(appName);
            if (Objects.nonNull(appByName)){
                List<UpmsResource> appResource = resourcesByUser.stream().filter(r -> Objects.nonNull(r.getAppId()) && r.getAppId() == appByName.getId()).collect(Collectors.toList());
                return new AjaxResult(true, appResource);
            }
        }
        return null;
    }

    /**
     * 获取所有已注册系统
     * @return
     */
    @ResponseBody
    @PostMapping("applist")
    public AjaxResult listAllSystem(AppVo appVo){
        Pager<App> applicationIsEnable = applicationService.findPage(appVo);
        return new AjaxResult(true,applicationIsEnable);
    }

    /**
     * 获取所有已注册系统
     * @return
     */
    @GetMapping("applist")
    public String listAllSystem(Model model){
        model.addAttribute("status",Status.values());
        return "application/app-pagination";
    }

    /**
     * 获取所有已启动系统
     * @return
     */
    @GetMapping("findEnableSystem")
    @ResponseBody
    public AjaxResult findEnable(){
        List<App> applicationIsEnable = applicationService.findApplicationIsEnable();
        return new AjaxResult(true,applicationIsEnable);
    }
}
